using Microsoft.AspNetCore.Mvc;
using MVCDemoSoft1.Repository;
using MVCDemoSoft1.Models;
using System.Linq;
using MVCDemoSoft1.RequestParam;
using System.Collections.Generic;

namespace MVCDemoSoft1.Controllers
{
    public class AccountController : Controller
    {
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            var accountRepositgory = new EfRepository<BankAccount>();
            var accounts = accountRepositgory.Table.Where(x => x.IsDeleted == false).ToList();
            return View(accounts);
        }
        public IActionResult CreateOrEdit(int id)
        {
            var accountRep = new EfRepository<BankAccount>();
            var account = accountRep.Table.Where(x => x.Id == id).FirstOrDefault();
            return View(account);
        }
        [HttpPost]
        public IActionResult Save(AccountRequest model)
        {
            var accountRepositgory = new EfRepository<BankAccount>();
            // id大于0，说明应该对应编辑后的保存，否则就是新增保存
            if (model.Id > 0)
            {
                var account = accountRepositgory.GetById(model.Id);
                if (account != null)
                {
                    account.Account = model.Account;
                    account.Balance = model.Balance;
                    account.Remarks = model.Remarks;
                    accountRepositgory.Update(account);
                }
            }
            else
            {
                accountRepositgory.Insert(
                new BankAccount
                {
                    Account = model.Account,
                    Balance = model.Balance,
                    Remarks = model.Remarks,
                    PersonId = 3
                });
            }




            return Ok();
        }

        public IActionResult Query(AccountQueryRequest request)
        {
            var accountRep = new EfRepository<BankAccount>();
            List<BankAccount> accounts;
            // 判断有无传入关键字 有则需要再加上关键字作为查找条件
            if (request != null && request.Keyword != null && request.Keyword.Length > 0)
            {
                accounts = accountRep.Table
                            .Where(x => x.IsDeleted == false && (x.Account.Contains(request.Keyword) || x.Remarks.Contains(request.Keyword)))
                            .ToList();
            }
            else
            {
                accounts = accountRep.Table
            .Where(x => x.IsDeleted == false)
            .ToList();
            }


            return Json(accounts);
        }

        public IActionResult Delete(int id)
        {
            var accountRep = new EfRepository<BankAccount>();
            accountRep.Delete(id);
            return RedirectToAction("Index");
        }

    }
}